﻿using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;

namespace ModelRelationship.ManyToManyRelationship
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [InverseProperty("Student")]
        public List<CourseSelection> CourseSelectionsStu { get; set; } = new List<CourseSelection>();
    }

    public class Course
    {
        public int Id { get; set; }
        public string Name { get; set; }

        [InverseProperty("Course")]
        public List<CourseSelection> CourseSelectionsCou { get; set; } = new List<CourseSelection>();
    }

    public class CourseSelection
    {
        public int StudentId { get; set; }

        [ForeignKey("StudentId")]
        [InverseProperty("CourseSelectionsStu")]
        public Student Student { get; set; }

        public int CourseId { get; set; }

        [ForeignKey("CourseId")]
        [InverseProperty("CourseSelectionsCou")]
        public Course Course { get; set; }

        public DateTimeOffset SelectionTime { get; set; }
    }

    /// <summary>
    /// 多对多关系显示映射配置
    /// </summary>
    public class ManyToManyRelationshipDbContext : DbContext
    {
        public DbSet<Student> Students => Set<Student>();
        public DbSet<Course> Courses => Set<Course>();
        public DbSet<CourseSelection> CourseSelections => Set<CourseSelection>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>(b =>
            {
                b.HasMany(s => s.CourseSelectionsStu)
                .WithOne(c => c.Student)
                .HasForeignKey(cs => cs.StudentId);
            });

            modelBuilder.Entity<Course>(b =>
            {
                b.HasMany(s => s.CourseSelectionsCou)
                .WithOne(c => c.Course)
                .HasForeignKey(cs => cs.CourseId);
            });

            modelBuilder.Entity<CourseSelection>(b =>
            {
                b.HasKey(cs => new { cs.StudentId, cs.CourseId });

                b.HasOne(cs => cs.Student)
                .WithMany(s => s.CourseSelectionsStu)
                .HasForeignKey(cs => cs.StudentId);

                b.HasOne(cs => cs.Course)
                .WithMany(s => s.CourseSelectionsCou)
                .HasForeignKey(cs => cs.CourseId);
            });
        }

    }
}
